﻿using Microsoft.ManagementConsole;
using SharpShare.Configuration;
using System.Configuration;
using System.Collections.Generic;
using System;
using System.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.Drawing;
using SharpShare.Activation;

namespace SharpShare.Management.Mmc.Views {
    public class ConfigurationListView<TBase, T> : MmcListView
        where TBase : IExtension
        where T : TBase, new() {
        public ConfigurationListView() {
            
        }

        public IExtensionFactory<TBase> ExtensionFactory {
            get {
                return (this.ViewDescriptionTag as IExtensionFactory<TBase>);
            }
        }

        private void Refresh() {

            this.ResultNodes.Clear();

            foreach (T element in this.ExtensionFactory.ListExtensions().OfType<T>()) {
                ResultNode node = new ResultNode();

                node.Tag = element;

                foreach (MmcListViewColumn column in this.Columns) {
                    ListPropertyColumn propColumn = (column as ListPropertyColumn);

                    if (propColumn == null) {
                        var nameProperty = this.ListElementProperties().Where(p => p.Name.Equals("Name", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                        if (nameProperty == null) {
                            node.DisplayName = "-";
                        } else {
                            node.DisplayName = (nameProperty.Property.GetValue(element, null).AsString());
                        }

                        if (string.IsNullOrWhiteSpace(node.DisplayName)) {
                            node.DisplayName = "(untitled)";
                        }

                        continue;
                    }

                    if (!propColumn.Info.Property.DeclaringType.IsAssignableFrom(element.GetType())) {
                        node.SubItemDisplayNames.Add("-");
                        continue;
                    }

                    object value = propColumn.Info.Property.GetValue(element, null);
                    string valueString = null;

                    if (value == null) {
                        valueString = "(null)";
                    } else {
                        valueString = value.ToString();
                    }

                    node.SubItemDisplayNames.Add(valueString);
                }

                this.ResultNodes.Add(node);
            }
        }

        protected override void OnInitialize(AsyncStatus status) {
            base.OnInitialize(status);

            this.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action(
             "Add...", "Add a new extension.", -1, "Add"));

            this.Columns.Clear();

            foreach (ListPropertyInfo propInfo in this.ListElementProperties()) {
                if (propInfo.Name.Equals("Name", StringComparison.OrdinalIgnoreCase))
                    continue;

                ListPropertyColumn column = new ListPropertyColumn(propInfo);
                this.Columns.Add(column);
            }

            this.Columns[0].SetWidth(100);

            this.Mode = MmcListViewMode.Report;

            this.Refresh();
        }
        protected override void OnSelectionChanged(SyncStatus status) {
            if (SelectedNodes.Count == 0) {
                this.SelectionData.Clear();
                this.SelectionData.EnabledStandardVerbs = StandardVerbs.None;
            } else {
                this.SelectionData.Update(this.SelectedNodes[0], false, null, null);
                this.SelectionData.EnabledStandardVerbs = StandardVerbs.Delete | StandardVerbs.Properties;
            }
        }
        protected override void OnAddPropertyPages(PropertyPageCollection propertyPageCollection) {
            PropertyGrid grid = new PropertyGrid();
            grid.Dock = DockStyle.Fill;
            grid.PropertySort = PropertySort.Alphabetical;
            grid.SelectedObject = this.SelectedNodes[0].Tag;
            grid.Size = new Size(410, 450);
            grid.PropertyValueChanged += new PropertyValueChangedEventHandler(PropertyGridPropertyValueChanged);
            grid.Font = new Font("Tahoma", 8.0f);

            PropertyPage page = new ConfigurationPropertyPage(this) {
                Title = "Settings",
                Control = grid
            };

            propertyPageCollection.Add(page);

            this.IsModified = true;
        }

        private void PropertyGridPropertyValueChanged(object s, PropertyValueChangedEventArgs e) {
            ((SharpShareSnapIn)this.SnapIn).ConfigurationChanged = true;
        }

        protected override void OnDelete(SyncStatus status) {
            base.OnDelete(status);

            T element = (T)this.SelectedNodes[0].Tag;
            this.ExtensionFactory.RemoveExtension(element);
            this.Refresh();

            ((SharpShareSnapIn)this.SnapIn).ConfigurationChanged = true;
        }
        protected override void OnAction(Microsoft.ManagementConsole.Action action, AsyncStatus status) {
            base.OnAction(action, status);

            switch ((string)action.Tag) {
                case "Add": {
                        T newExtension = new T();
                        this.ExtensionFactory.AddExtension(newExtension);
                        this.Refresh();

                        var newResultNode = this.ResultNodes.Cast<ResultNode>().Where(n => n.Tag.Equals(newExtension)).FirstOrDefault();

                        if (newResultNode != null) {
                            newResultNode.SendSelectionRequest(true);
                        }

                        break;
                    }
            }
        }
        protected override void OnRefresh(AsyncStatus status) {
            base.OnRefresh(status);
            this.Refresh();
        }

        private IEnumerable<ListPropertyInfo> ListElementProperties() {
            var infos =
                new Type[] { typeof(T) }
                .SelectMany(t => t.GetProperties(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy))
                .Select(p => {
                    ConfigurationPropertyAttribute configPropAttr = p.GetCustomAttribute<ConfigurationPropertyAttribute>();
                    if (configPropAttr == null)
                        return null;

                    DisplayNameAttribute displayNameAttr = p.GetCustomAttribute<DisplayNameAttribute>();

                    ListPropertyInfo info = new ListPropertyInfo() {
                        Name = configPropAttr.Name,
                        ConfigurationPropertyAttribute = configPropAttr,
                        Property = p
                    };

                    if (displayNameAttr != null)
                        info.Name = displayNameAttr.DisplayName;

                    return info;
                })
                .Where(i => i != null);

            return infos;
        }

        private class ListPropertyColumn : MmcListViewColumn {
            public ListPropertyColumn(ListPropertyInfo info) {
                this.Info = info;
                this.Title = info.Name;
            }

            public ListPropertyInfo Info { get; private set; }
        }

        private class ListPropertyInfo {
            public string Name { get; set; }
            public PropertyInfo Property { get; set; }
            public ConfigurationPropertyAttribute ConfigurationPropertyAttribute { get; set; }
        }

        private class ConfigurationPropertyPage : PropertyPage {
            public ConfigurationPropertyPage(ConfigurationListView<TBase, T> listView) {
                this.ListView = listView;
            }

            public ConfigurationListView<TBase, T> ListView { get; private set; }

            protected override void OnDestroy() {
                base.OnDestroy();
                this.ListView.Refresh();
            }

            protected override void OnInitialize() {
                base.OnInitialize();
                this.ParentSheet.CancelToClose();
            }
        }
    }
}
